package com.atguigu.gulimail.seckill.dubbo;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.service.seckill.SecKillDubboService;
import com.atguigu.common.utils.R;
import com.atguigu.gulimail.seckill.to.SeckillSkuRedisTo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Date;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @author fangy
 * @date 2022-10-25 11:41
 */
@DubboService
public class SeckillDubboServiceImpl implements SecKillDubboService {


    @Autowired
    StringRedisTemplate redisTemplate;

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";


    @Override
    public R getSecKillSkus(Long SkuId) {

        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        Set<String> keys = ops.keys();

        if(keys != null && keys.size() > 0){

            String regx = "\\d_"+SkuId;
            for (String key: keys) {
                if(Pattern.matches(regx,key)){
                    String s = ops.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);

                    long current = new Date().getTime();

                    if(current>=redisTo.getStartTime() && current<= redisTo.getEndTime()){

                    }else{
                        redisTo.setRandomCode(null);
                    }
                    return R.ok().setData(redisTo);
                }
            }

        }

        return null;

    }
}
